package common.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import common.exception.RRException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 * <p>阿里云短信</p>
 *@author zwy
 *@date 2025/3/9 17:41
*/

public class AliyunUtils {
    //阿里云id
    private static final String ACCESSKEYID = "";

    //阿里云密钥
    private static final String ACCESSKEYSECRET = "";

    //注册 获取验证码 模板code
    private static final String TEMPLATECODE = "";

    //签名
    private static final String SINGNAME = "";

    /**
     * 阿里云短信 注册发送验证码
     * 引入：aliyun-java-sdk-core
     *
     * @param phone 手机号 国内短信：11位手机号码；；国际/港澳台消息：国际区号+号码，例如85200000000。
     * @param code  验证码 随机数自己生成
     * @return
     */
    public static String sendSMS(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESSKEYID, ACCESSKEYSECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SINGNAME);
        request.putQueryParameter("TemplateCode", TEMPLATECODE);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response);
            JSONObject returndata = JSON.parseObject(response.getData());

            if (("OK").equals(returndata.getString("Code"))) {
                ///发送成功
                return "success";
            } else {
                ///发送失败
                return "error";
            }
        } catch (ClientException e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 全球快递物流查询
     * 参考文档地址：https://market.aliyun.com/products/57126001/cmapi026963.html?spm=5176.10695662.1996646101.searchclickresult.4fe2b8efi3TJBR#sku=yuncode2096300000
     *
     * @param appcode 开通服务后 买家中心-查看AppCode
     * @param no      快递单号 【顺丰请输入单号 : 收件人或寄件人手机号后四位。例如：123456789:1234】
     * @param type    快递公司字母简写：不知道可不填 95%能自动识别，填写查询速度会更快
     */
    public static Map<String, Object> goexpress(String appcode, String no, String type) {
        //请求地址 支持http 和 https 及 WEBSOCKET
        String host = "https://goexpress.market.alicloudapi.com";
        // 后缀
        String path = "/goexpress";
        //AppKey：203951267     AppSecret：pfk1W5FvvWTDXfbgziNbfJieJj7Xrsin
        //appcode e8b0bcf5bf294f58afe212fb2b817cb1
        //拼接请求链接
        String urlSend = host + path + "?no=" + no + "&type=" + type;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            //// 格式Authorization:APPCODE
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);
            // (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(json);
                Map<String, Object> map2 = JSON.parseObject(json, Map.class);
                System.out.print(map2);
                return map2;
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && "Invalid AppCode `not exists`".equals(error)) {
                    System.out.println("AppCode错误 ");
                    throw new RRException("AppCode错误 ");
                } else if (httpCode == 400 && "Invalid Url".equals(error)) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                    throw new RRException("请求的 Method、Path 或者环境错误 ");
                } else if (httpCode == 400 && "Invalid Param Location".equals(error)) {
                    System.out.println("参数错误");
                    throw new RRException("参数错误");
                } else if (httpCode == 403 && "Unauthorized".equals(error)) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                    throw new RRException("服务未被授权（或URL和Path不正确） ");
                } else if (httpCode == 403 && "Quota Exhausted".equals(error)) {
                    System.out.println("套餐包次数用完 ");
                    throw new RRException("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                    throw new RRException(error);
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
            throw new RRException("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
            throw new RRException("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            e.printStackTrace();
            throw new RRException(e.getMessage());
        }
    }


    /**
     * 读取返回结果
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
